package repository

import (
	"context"
	"time"

	"gitee.com/thewalkers/refactoring-code/model"
	"gitee.com/thewalkers/refactoring-code/model/apperrors"
	"github.com/jmoiron/sqlx"
	"go.uber.org/zap"
)

// MysqlTimeCardRepository s data/repository implementation
// of service layer EmployeeRepository
type MysqlTimeCardRepository struct {
	DB *sqlx.DB
}

// NewTimeCardRepository s a factory for initializing Employee Repository
func NewTimeCardRepository(db *sqlx.DB) model.TimeCardRepository {
	return &MysqlTimeCardRepository{
		DB: db,
	}
}

func (m *MysqlTimeCardRepository) Create(ctx context.Context, t *model.TimeCard) error {
	query := `INSERT INTO time_card(hour_classification_id, hours) VALUES(?, ?)`

	if _, err := m.DB.Exec(query, t.HourClassificationID, t.Hours); err != nil {
		zap.L().Error("repository cound not create a time card with err: ", zap.Error(err))
		return apperrors.NewInternal()
	}

	return nil
}

func (m *MysqlTimeCardRepository) GetDate(ctx context.Context, id int64) (time.Time, error) {
	timeCard := &model.TimeCard{}

	query := `SELECT * FROM time_card where id = ?`
	if err := m.DB.Get(timeCard, query, id); err != nil {
		zap.L().Error("repository could not get a time card with err:", zap.Error(err))
		return timeCard.DateTime, apperrors.NewInternal()
	}

	return timeCard.DateTime, nil
}

func (m *MysqlTimeCardRepository) GetHours(ctx context.Context, id int64) (float64, error) {
	timeCard := &model.TimeCard{}

	query := `SELECT * FROM time_card where id = ?`
	if err := m.DB.Get(timeCard, query, id); err != nil {
		zap.L().Error("repository could not get a time card with err:", zap.Error(err))
		return timeCard.Hours, apperrors.NewInternal()
	}

	return timeCard.Hours, nil
}
